from PIL import Image
import os


def batch_convert_bmp_to_jpg(input_folder, output_folder, quality=90):
    """
    批量将文件夹中的BMP转换为JPG

    参数:
        input_folder: 输入文件夹路径
        output_folder: 输出文件夹路径
        quality: JPG质量(1-100)
    """
    # 创建输出文件夹（如果不存在）
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 统计变量
    success_count = 0
    fail_count = 0

    # 遍历文件夹
    for filename in os.listdir(input_folder):
        # 检查是否是BMP文件
        if filename.lower().endswith('.bmp'):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(
                output_folder,
                os.path.splitext(filename)[0] + '.jpg'
            )

            try:
                # 打开并转换图像
                with Image.open(input_path) as img:
                    if img.mode != 'RGB':
                        img = img.convert('RGB')
                    img.save(output_path, 'JPEG', quality=quality)
                print(f"✓ 成功转换: {filename}")
                success_count += 1
            except Exception as e:
                print(f"✗ 转换失败 {filename}: {str(e)}")
                fail_count += 1

    # 输出统计结果
    print(f"\n转换完成: 成功 {success_count} 个, 失败 {fail_count} 个")


# 使用示例
# inp = r'C:\Users\Admin\MVS\Data\MV-CH250-90GM (DA4906765)'
# outp = r'C:\Users\Admin\MVS\Data\MV-CH250-90GM (DA4906765)_jpg'


inp = r'C:\Users\Admin\MVS\Data\MV-CH250-90GM (DA4621358)'
outp = r'C:\Users\Admin\MVS\Data\MV-CH250-90GM (DA4621358)_jpg'
batch_convert_bmp_to_jpg(inp, outp)